package com.caunock.sqlbuilder.adapter;


import com.caunock.sqlbuilder.adapter.group.impl.*;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 适配器持有者
 * @author Qinweitong
 */
@Component
public class DDLAdapterHolder implements CommandLineRunner {

    /**
     * 项目注册adapter用来覆盖adapters
     */
    public static Map<String, DDLAdapter> adapters = new LinkedHashMap<>();

    /**
     * 注册适配器
     *
     * @param dbType  数据库类型
     * @param adapter 适配器
     */
    public static void register(String dbType, DDLAdapter adapter) {
        adapters.put(dbType, adapter);
    }

    /**
     * 获取适配器
     *
     * @param dbType 数据库类型
     * @return DriverAdapter
     */
    public static DDLAdapter getAdapter(String dbType) {
        DDLAdapter DDLAdapter = adapters.get(dbType);
        if (Objects.isNull(DDLAdapter)) {
            throw new RuntimeException("[检测数据库适配器] 检测失败, 无可用的适配器 " + dbType);
        }
        return DDLAdapter;
    }

    @Override
    public void run(String... args) {
        register("DM", new DMAdapter());
        register("DB2", new DB2Adapter());
        register("GreatDB", new GreatDBAdapter());
        register("KingBase", new GreatDBAdapter());
        register("MariaDB", new MariaDBAdapter());
        register("MySQL", new MySQLAdapter());
        register("Oracle", new OracleAdapter());
        register("PostgreSQL", new PostgreSQLAdapter());
        register("SQLite", new SQLiteAdapter());
    }
}
